package pers.vic.upload.business.service.impl;

import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.tool.Tools;
import org.springframework.stereotype.Service;
import pers.vic.upload.business.model.AssertModel;
import pers.vic.upload.business.model.WarrantModel;
import pers.vic.upload.business.service.BaseBusinessService;
import pers.vic.upload.constant.FileType;
import pers.vic.upload.constant.FinalFiledParams;
import pers.vic.upload.constant.ResultEnum;
import pers.vic.upload.login.model.User;
import pers.vic.upload.utils.SessionHelper;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述:权证业务处理
 * @author Vic.xu
 * @date 2022-07-25 9:39
 */
@Service
public class WarrantModelServiceImpl extends BaseBusinessService<WarrantModel> {


    private static final int FILENAME_FRAGMENT = 4;

    /*
     校验文件名称的“识别号+证书类型+起始日期+截止日期”
      ICBCSTL-68545
      命名规则：
      识别号_保险类型（对应英文）_起始日期-截止日期；   保险
      识别号_证书类型（对应英文）_起始日期-截止日期；   权证
      具体类型对应英文参照01；命名规则参照02
     */

    @Override
    public FileType type() {
        return FileType.warrant;
    }

    @Override
    public BaseResponse<WarrantModel> check(String fileName, boolean ignoreUnique) {
        Map<Integer, String> map = splitFileName(fileName);
        if (map == null || map.size() != FILENAME_FRAGMENT) {
            return BaseResponse.error("不合法的文件名");
        }
        WarrantModel model = new WarrantModel();
        //1 识别号 放在最后
        String identityCode = map.get(1);
        model.setIdentityCode(identityCode);
        AssertModel asset = findAsset(identityCode);
        if ( asset == null) {
            return BaseResponse.error("系统中不存在的识别号:" + identityCode);
        }
        model.setFkAssetId(asset.getId());
        model.setIdentityMethod(asset.getMethod());
        model.setOwnership(asset.getOwnership());
        model.setShipFlag(asset.getShipFlag());
        model.setShipPort(asset.getRegPort());

        // check 证书类型
        String certificateType = map.get(2);

        BaseResponse<String> certificateTypeCheck = queryOptionValue(FinalFiledParams.PCODE_MECERTIFICATETYPE, certificateType);
        if (!certificateTypeCheck.isSuccess()) {
            return BaseResponse.error(certificateTypeCheck.getCode(), certificateTypeCheck.getMsg());
        }
        model.setCertificateType(certificateTypeCheck.getData());
        map.put(2, model.getCertificateType());
        String startDateStr = map.get(3);
        if (isNotDate(startDateStr)) {
            return BaseResponse.error("不合法的起始日期");
        }
        Date startDate = toDate(startDateStr);
        model.setStartDate(startDate);
        String endDateStr = map.get(4);
        if (isNotDate(endDateStr)) {
            return BaseResponse.error("不合法的起始日期");
        }
        Date endDate = toDate(endDateStr);
        if (endDate.before(startDate)) {
            return BaseResponse.error("截止日期大于起始日期");
        }
        model.setEndDate(endDate);

        //check  识别号 放在最后检测
        if (!ignoreUnique && existFileNameDataCheck(map)) {
            return BaseResponse.error(ResultEnum.EXISTED_IDENTITY_CODE);
        }
        model.setIdentityCode(identityCode);
        return BaseResponse.success(model);
    }

    @Override
    protected boolean existFileNameDataCheck(Map<Integer, String> map) {
        String sql = "select  count(1)   " +
                " from  T_MPL_WARRANT_MANAGE a " +
                " where a.identity_code = ? " +
                " and a.certificate_type = ?  " +
                " and to_char(a.start_date, 'YYYYMMDD') = ?" +
                " and to_char(a.end_date, 'YYYYMMDD') = ?";
        Integer num = jdbcTemplate.queryForObject(sql, Integer.class, map.get(1), map.get(2), map.get(3), map.get(4));
        return num != null && num > 0;
    }


    @Override
    public String save(WarrantModel model) {
        String id = Tools.randomUuid();
        String userId = SessionHelper.userId();
        User user = SessionHelper.getSocketThreadUserWithoutNull();
        model.setId(id);
        String sql = "insert into T_MPL_WARRANT_MANAGE" +
                "(ID, CREATE_DATE, Create_User_Id, ENABLE_FLAG, LAST_UPDATE_DATE, LAST_UPDATE_USER_ID, " +
                " IDENTITY_CODE, CERTIFICATE_TYPE, Start_Date, End_Date, IDENTITY_METHOD," +
                " Status, fk_asset_id, fk_organization_id, fk_legal_organization_id, FK_OWNER_ID," +
                " OWNERSHIP, SHIP_FLAG, SHIP_PORT) " +
                "values(?, sysdate, ?, 1, sysdate, ?," +
                " ?, ?, ?,?,?, " +
                " ?, ?, ?,?,?," +
                " ?, ?, ?)";
        Object[] params = {id, userId, userId,
                model.getIdentityCode(), model.getCertificateType(), model.getStartDate(), model.getEndDate(),model.getIdentityMethod(),
                STATUS, model.getFkAssetId(), user.getFkOrganizationId(), user.getFkOrgCompanyId(), userId,
        model.getOwnership(), model.getShipFlag(), model.getShipPort()};
        jdbcTemplate.update(sql, params);
        return id;


    }

    @Override
    public void saveRelation(String id, String attachmentId) {
        attachmentService.insertRelation("T_MPL_WARRANT_ATTACH","FK_WARRANT_ID", id, "FK_ATTACH_ID", attachmentId);
    }

    /**
     * 识别号是否存在
     * @param identityCode identityCode
     * @return exist？
     */
    @Override
    public boolean identityCodeCheck(String identityCode) {
        String sql = "select count(1) from  T_MPL_WARRANT_MANAGE a where a.identity_code = ?";
        Integer num = jdbcTemplate.queryForObject(sql, Integer.class, identityCode);
        return num != null && num > 0;
    }

    @Override
    public List<Map<String, Object>> find() {
        String sql = "select c.file_name,c.original_file_name,c.file_path, a.* " +
                "from T_MPL_WARRANT_MANAGE a  " +
                "left join  T_MPL_WARRANT_ATTACH b on a.id = b.fk_warrant_id " +
                "left join   T_STL_S_ATTACHMENT c on c.id =b.fk_attach_id " +
                "where 1=1  order by a.create_date desc  ";
        sql = MessageFormat.format("select * from ({0} ) where rownum < 11", sql);
        return jdbcTemplate.queryForList(sql);
    }

}
